define([ './module' ], function(goodscategorymodule) {
	'use strict';


	goodscategorymodule.controller('goodscategory',['$window','$scope','$http','$location','GoodsTypeService','Upload','$timeout',function($window,$scope,$http,$location,GoodsTypeService,Upload,$timeout){
		//查询所有商品类型
		$scope.findallgoodstype=function(){
			var promise=GoodsTypeService.query();
			promise.then(function(data){
				$scope.goodstypeselect=data.beanlist;
			},function(data){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}

		//查询所有一级商品分类
		$scope.findallnavcategoryt=function(){
			$http({
				method:'POST',
				url:'../mall/goodscategory/findNavAll'
			}).
			success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.navall=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}

		//查询所有二级商品分类
		$scope.findallltypecategoryt=function(){
			$http({
				method:'POST',
				url:'../mall/goodscategory/findLtypeAll'
			}).
			success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.ltypeall=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}




		//监听files进行图片上传
		$scope.$watch('files',function(){
			$scope.upload($scope.files);
		});
		$scope.allupimgs=[];
		$scope.upload=function(files){
			if(files&&files.length){
				for(var i=0;i<files.length;i++){
					var file=files[i];
					var filename=files[i].name;
					if(!file.$error){
						Upload.upload({
							url:'../mall/files/ajaxFileUploadsImgs',
							data:{
								file:file,
								'filename':filename
							}
						}).progress(function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $scope.progress=progressPercentage;
            }).success(function (data, status, headers, config) {
                $timeout(function() {
                	if(data.ifb.sucflag){
                		$scope.allupimgs.push(data.ifb);
                	}
                });
            });
					}
				}
			}
		}

		$scope.remove=function(index){
			$scope.allupimgs.splice(index,1);
		}



		$scope.gradechange=function(){
			var localgrade=$scope.grade;
			switch (localgrade) {
				case 0:
					$scope.ltypeidcategoryshow=false;
					$scope.stypeidcategoryshow=false;
					break;
				case 1:
					$scope.ltypeidcategoryshow=true;
					$scope.stypeidcategoryshow=false;
					break;
				case 2:
					$scope.ltypeidcategoryshow=false;
					$scope.stypeidcategoryshow=true;
					break;
				default:
			}
		}
		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			//隐藏修改商品类型按钮
			$scope.modifygoodstypeshow=false;
			//显示商品类型选择
			$scope.goodstypeshow=true;
			//隐藏上一个商品类型名称
			$scope.lastgoodstypenameshow=false;
			//隐藏父分类名称
			$scope.parentnameshow=false;

			$scope.title='添加商品分类';
			//设置分类默认一级
			$scope.grade="0";
			//记录状态
			$scope.status="1";
			//同步移动平台
			$scope.msync="1";
			$scope.sort=1;

			//修改商品名称时自动填充搜索关键字和描述
			$scope.$watch('name',function(){
				$scope.metakey=$scope.metades=$scope.name;
			});


			//保存数据方法
			$scope.save=function(){
				if(validate()){
					var parentid="";
					var parentname="";
					var path="";
					switch ($scope.grade) {
						case 0:
							parentid="";
							parentname="";
							path="";
							break;
						case 1:
							parentid=$scope.navallx.id;
							parentname=$scope.navallx.name;
							path=parentid;
							break;
						case 2:
							parentid=$scope.ltypeallx.id;
							parentname=$scope.ltypeallx.name;
							path=parentid;
							break;
						default:
					}
					var goodstypeid=$scope.selectedgoodstype.goodstypeid;
					var goodstypename=$scope.selectedgoodstype.name;
					var grade=$scope.grade;
					var logo=angular.toJson($scope.allupimgs);
					var metades=$scope.metades;
					var metakey=$scope.metakey;
					var msync=$scope.msync;
					var name=$scope.name;
					var status=$scope.status;
					var sort=$scope.sort;
					$http({
						method:'POST',
						url:'../mall/goodscategory/save',
						data:{
							'goodstypeid':goodstypeid,
							'goodstypename':goodstypename,
							'grade':grade,
							'logo':logo,
							'metades':metades,
							'metakey':metakey,
							'msync':msync,
							'parentid':parentid,
							'parentname':parentname,
							'path':path,
							'sort':sort,
							'name':name,
							'status':status
						}
					}).
					success(function(data,status,headers,config){
						if(data.sucflag){
							$scope.info={
									show:true,
									msg:'商品分类添加成功'
							}
							$location.path('/goodscategoryment');
						}else{
							$scope.errors={
									show:true,
									msg:data.msg
							}
						}
					}).
					error(function(data,status,headers,config){
						$scope.errors={
								show:true,
								msg:'系统异常'
						}
					});
				}
			}
		}
		//如果operate是edit则执行保存行为
		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/goodscategory/find',
					data:{
						'id':id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对商品分类--'+data.bean.name+'--进行编辑';
						$scope.lastgoodstypename=data.bean.goodstypename;//上一个商品分类名称
						$scope.lastgoodstypeid=data.bean.goodstypeid;//上一个商品分类id
						$scope.grade=data.bean.grade;
						if(data.bean.grade=="0"){
							$scope.parentnameshow=false;
						}else{
							//上级分类id
							$scope.parentid=data.bean.parentid;
							$scope.parentname=data.bean.parentname;
							$scope.parentnameshow=true;
						}
						$scope.name=data.bean.name;
						$scope.readonlyname=true;
						$scope.allupimgs.push(data.ifb);
						$scope.metakey=data.bean.metakey;
						$scope.metades=data.bean.metades;
						$scope.sort=data.bean.sort;
						$scope.msync=data.bean.msync;
						$scope.status=data.bean.status;
						$scope.updatebtn={show:true};
						//显示修改商品类型按钮
						$scope.modifygoodstypeshow=true;
						//隐藏商品类型选择
						$scope.goodstypeshow=false;
						//显示上一个商品类型名称
						$scope.lastgoodstypenameshow=true;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

				//点击修改商品类型按钮
				$scope.clickmodifygoodstype=function(){
					$scope.goodstypeshow=true;
				}



				//更新数据方法
				$scope.update=function(){
					if(validate()){
						var localgrade=$scope.grade+"";
						var parentid="";
						var parentname="";
						var path="";
						switch (localgrade) {
							case "0":
								break;
							case "1":
								if($scope.ltypeidcategoryshow){
									parentid=$scope.navallx.id;
									parentname=$scope.navallx.name;
									path=parentid;
								}else{
									parentid=$scope.parentid;
									parentname=$scope.parentname;
									path=parentid;
								}
								break;
							case "2":
								if($scope.stypeidcategoryshow){
									parentid=$scope.ltypeallx.id;
									parentname=$scope.ltypeallx.name;
									path=parentid;
								}else{
									parentid=$scope.parentid;
									parentname=$scope.parentname;
									path=parentid;
								}

								break;
							default:
						}

						if($scope.goodstypeshow){
							if($scope.selectedgoodstype==undefined){
								$scope.errors={
									show:true,
									msg:"请选择商品分类"
								}
								return false;
							}
							var goodstypeid=$scope.selectedgoodstype.goodstypeid;
							var goodstypename=$scope.selectedgoodstype.name;
						}else{
							var goodstypeid=$scope.lastgoodstypeid;
							var goodstypename=$scope.lastgoodstypename;
						}
						var grade=$scope.grade;
						var logo=angular.toJson($scope.allupimgs);
						var metades=$scope.metades;
						var metakey=$scope.metakey;
						var msync=$scope.msync;
						var name=$scope.name;
						var status=$scope.status;
						var sort=$scope.sort;
						$http({
							method:'POST',
							url:'../mall/goodscategory/update',
							data:{
								'goodstypeid':goodstypeid,
								'goodstypename':goodstypename,
								'grade':grade,
								'logo':logo,
								'metades':metades,
								'metakey':metakey,
								'msync':msync,
								'parentid':parentid,
								'parentname':parentname,
								'path':path,
								'sort':sort,
								'name':name,
								'status':status,
								'id':id
							}
						}).
						success(function(data,status,headers,config){
							if(data.sucflag){
								$scope.info={
										show:true,
										msg:'商品分类更新成功'
								}
								$location.path('/goodscategoryment');
							}else{
								$scope.errors={
										show:true,
										msg:data.msg
								}
							}
						}).
						error(function(data,status,headers,config){
							$scope.errors={
									show:true,
									msg:'系统异常'
							}
						});
					}
				}

			}


		}
		//表单字段验证
		function validate(){
			var name=$scope.name;
			if(name==undefined||name==""){
				$scope.errors={
						show:true,
						msg:"请输入商品分类名称"
				}
				return false;
			}
			var metakey=$scope.metakey;
			if(metakey==undefined||metakey==""){
				$scope.errors={
					show:true,
					msg:"请输入搜索引擎关键字"
				}
				return false;
			}
			var metades=$scope.metades;
			if(metades==undefined||metades==""){
				$scope.errors={
					show:true,
					msg:"请输入搜索引擎描述"
				}
				return false;
			}
			var sort=$scope.sort;
			if(sort==undefined||sort==""){
				$scope.errors={
					show:true,
					msg:"请输入排序"
				}
				return false;
			}


			return true;
		}
	}]);



	goodscategorymodule.controller('goodscategoryment',ServerGoodsTypeListCtrl);
	
	
	//查询列表数据
	function ServerGoodsTypeListCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=
			DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/goodscategory/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',false)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
    .withOption('stateSave', true)
    .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){
			
		});
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
		              }),
	              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
								DTColumnBuilder.newColumn(null).withTitle('图标').notSortable().renderWith(logoHtml),
			          DTColumnBuilder.newColumn('name').withTitle('名称').notSortable(),
								DTColumnBuilder.newColumn('grade').withTitle('分类等级').notSortable(),
								DTColumnBuilder.newColumn('parentname').withTitle('上级分类').notSortable(),
								DTColumnBuilder.newColumn('sort').withTitle('排序').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];

		function logoHtml(data,type,full,meta){
			return '<img class="img-responsive pad" ng-src="'+data.slogo+'" alt="Photo" />';
		}
		function actionHtml(data,type,full,meta){
			return '<button class="btn btn-warning" ng-click="edit('+data.id+')"><i class="fa fa-edit"></i></button>';
		}
		function reloadData(){
			var resetPaging = false;
			vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}


		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/goodscategory').search({'operate':'edit','id':id});
		}

		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/goodscategory').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/goodscategory/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}
		


	}
});
